package com.tjetc.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.tjetc.constant.RedisConstant;
import com.tjetc.entity.po.User;
import com.tjetc.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.Duration;
import java.util.Map;
import java.util.Objects;

import static com.tjetc.constant.RedisConstant.LOGIN_TOKEN_TTL;

/**
 * @author gaoyongxiang
 * @version v1.0
 * @since 2025-10-20
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {
    private RedisTemplate<String, Object> redisTemplate;

    public RefreshTokenInterceptor(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 校验请求是否携带token
        String token =  request.getHeader("Authentication");
        if (StrUtil.isBlankIfStr(token)) {
            // 直接放行 说明就没登录过
            return true;
        }
        // 和redis中进行校验 判断用户是否存在
        String tokenKey = RedisConstant.LOGIN_TOKEN + token;

        // 校验redis中是否存在用户
        Map<Object, Object> userMap = redisTemplate.opsForHash().entries(tokenKey);
        // 如果不存在用户 直接放行
        if (userMap.isEmpty()) {
            return true;
        }
//        User user = new User();
        // 将用户信息保存到UserContext中
//        userMap.forEach((k, v) -> {
//            if ("userId".equals(k)) {
//                user.setUserId((Integer) v);
//            }
//        });
        User user = BeanUtil.fillBeanWithMap(userMap, new User(), false);
        UserContext.saveUser(user);
        // 刷新token
        redisTemplate.expire(tokenKey, Duration.ofMinutes(LOGIN_TOKEN_TTL));
        return true;
    }


}
